﻿using System;
using System.Configuration;
using System.Threading;
using Microsoft.Rtc.Sip;

namespace PlusRemover
{
    class Program
    {
        static void Main(string[] args)
        {
            bool modifyFromHeader = false;
            bool modifyToHeader = false;

            // Get settings from the App.config.
            modifyFromHeader = bool.Parse(ConfigurationManager.AppSettings["modifyFromHeader"]);
            modifyToHeader = bool.Parse(ConfigurationManager.AppSettings["modifyToHeader"]);

            PlusRemover serverApplication = new PlusRemover(modifyFromHeader, modifyToHeader);

            try
            {
                // Try to connect to the FE server several times.
                ServerAgent.WaitForServerAvailable(10);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            // Load the app manifest from the current directory where the application is running.
            Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            ApplicationManifest manifest = ApplicationManifest.CreateFromFile("PlusRemover.am");

            try
            {
                // Try to compile the manifest.
                manifest.Compile();
            }
            catch (CompilerErrorException ex)
            {
                Console.WriteLine(ex);
            }

            ServerAgent agent = null;
            try
            {
                // Set the PlusRemover object as the handler for messages.
                agent = new ServerAgent(serverApplication, manifest);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            if (agent != null)
            {
                Console.WriteLine("Plus remover has started successfully.");
                while (true)
                {
                    // Handle messages as they arrive.
                    agent.WaitHandle.WaitOne();
                    ThreadPool.QueueUserWorkItem(new WaitCallback(agent.ProcessEvent));
                }
            }
            else
            {
                Console.WriteLine("Failed to start.");
            }
        }
    }
}
